package GUIHelper;

import javax.swing.JPanel;
import javax.swing.JOptionPane;
import java.awt.BorderLayout;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import java.util.ArrayList;

import ControlLayer.*;
import GUILayer.LoginUI;
import ModelLayer.*;

import javax.swing.JTextField;
import java.awt.FlowLayout;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.border.TitledBorder;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class FacilityPanel extends JPanel {

	private boolean isNew = false;

	private JTable facilityTable;
	private DefaultTableModel modelFacility;
	private DefaultTableModel modelActivity;

	private JButton btnRefresh;
	private JButton buttonAddA;
	private JButton buttonRemoveA;
	private JButton btnNew;
	private JButton btnEdit;
	private JButton btnClear;
	private JButton btnSave;
	private JButton btnDelete;

	private JTextField textField;
	private JTextField facilityName;
	private JTextField facilityID;
	private JTable tableActivities;
	private int authLevel;

	public FacilityPanel() {
		setLayout(new BorderLayout(0, 0));
		authLevel = LoginUI.getLoggedInPosition();
		initialize();
	}

	private void initialize() {
		JPanel panel_facilityList = new JPanel();
		add(panel_facilityList, BorderLayout.WEST);
		panel_facilityList.setLayout(new BorderLayout(0, 0));

		JPanel panel_facilityDetail = new JPanel();
		add(panel_facilityDetail, BorderLayout.CENTER);
		panel_facilityDetail.setLayout(new BorderLayout(0, 0));

		JPanel panel_facility_details = new JPanel();
		panel_facility_details.setBorder(new TitledBorder(null,
				"Facility Details", TitledBorder.LEADING, TitledBorder.TOP,
				null, null));
		panel_facilityDetail.add(panel_facility_details, BorderLayout.NORTH);

		facilityName = new JTextField();
		facilityName.setEnabled(false);
		facilityName.setColumns(10);

		facilityID = new JTextField();
		facilityID.setEnabled(false);
		facilityID.setColumns(10);

		JLabel lblId = new JLabel("ID:");

		JLabel lblName = new JLabel("Name:");
		GroupLayout gl_panel_facility_details = new GroupLayout(
				panel_facility_details);
		gl_panel_facility_details
				.setHorizontalGroup(gl_panel_facility_details
						.createParallelGroup(Alignment.TRAILING)
						.addGroup(
								gl_panel_facility_details
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												gl_panel_facility_details
														.createParallelGroup(
																Alignment.LEADING)
														.addComponent(lblId)
														.addComponent(lblName))
										.addGap(56)
										.addGroup(
												gl_panel_facility_details
														.createParallelGroup(
																Alignment.LEADING)
														.addComponent(
																facilityName,
																GroupLayout.DEFAULT_SIZE,
																249,
																Short.MAX_VALUE)
														.addComponent(
																facilityID,
																GroupLayout.DEFAULT_SIZE,
																135,
																Short.MAX_VALUE))
										.addContainerGap()));
		gl_panel_facility_details
				.setVerticalGroup(gl_panel_facility_details
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								gl_panel_facility_details
										.createSequentialGroup()
										.addGroup(
												gl_panel_facility_details
														.createParallelGroup(
																Alignment.BASELINE)
														.addComponent(lblId)
														.addComponent(
																facilityID,
																GroupLayout.PREFERRED_SIZE,
																GroupLayout.DEFAULT_SIZE,
																GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(
												ComponentPlacement.RELATED)
										.addGroup(
												gl_panel_facility_details
														.createParallelGroup(
																Alignment.BASELINE)
														.addComponent(
																facilityName,
																GroupLayout.PREFERRED_SIZE,
																GroupLayout.DEFAULT_SIZE,
																GroupLayout.PREFERRED_SIZE)
														.addComponent(lblName))
										.addContainerGap(23, Short.MAX_VALUE)));
		panel_facility_details.setLayout(gl_panel_facility_details);

		JPanel panel_facility_activities = new JPanel();
		panel_facility_activities.setBorder(new TitledBorder(null,
				"Activities", TitledBorder.LEADING, TitledBorder.TOP, null,
				null));
		panel_facilityDetail
				.add(panel_facility_activities, BorderLayout.CENTER);

		JPanel panel_inside = new JPanel();
		GroupLayout gl_panel_facility_activities = new GroupLayout(
				panel_facility_activities);
		gl_panel_facility_activities
				.setHorizontalGroup(gl_panel_facility_activities
						.createParallelGroup(Alignment.TRAILING).addComponent(
								panel_inside, GroupLayout.DEFAULT_SIZE, 382,
								Short.MAX_VALUE));
		gl_panel_facility_activities
				.setVerticalGroup(gl_panel_facility_activities
						.createParallelGroup(Alignment.LEADING).addComponent(
								panel_inside, Alignment.TRAILING,
								GroupLayout.DEFAULT_SIZE, 346, Short.MAX_VALUE));
		panel_inside.setLayout(new BorderLayout(0, 0));

		modelActivity = new DefaultTableModel(new Object[][] {}, new String[] {
				"ID", "Name" }) {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};

		tableActivities = new JTable(modelActivity);
		tableActivities.setEnabled(false);
		tableActivities.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableActivities.getColumnModel().getColumn(0).setMaxWidth(100);
		tableActivities.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				System.out.println(tableActivities.getSelectedRowCount() + " "
						+ tableActivities.getSelectedRow());
				if (tableActivities.isEnabled()
						&& tableActivities.getSelectedRowCount() > 0) {
					buttonRemoveA.setEnabled(true);
				}
			}
		});
		panel_inside.add(new JScrollPane(tableActivities), BorderLayout.CENTER);

		JPanel panel_1 = new JPanel();
		panel_inside.add(panel_1, BorderLayout.SOUTH);

		if (authLevel == 1 || authLevel == 2 || authLevel == 3) {
			buttonRemoveA = new JButton("Remove");
			buttonRemoveA.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					ActivityType at = new ActivityTypeCtr()
							.getActivity((Long) modelActivity.getValueAt(
									tableActivities.getSelectedRow(), 0));
					if (JOptionPane.showConfirmDialog(null,
							"Confirm the removal of activity " + at.getName()
									+ " from facility #" + facilityID.getText()
									+ ", " + facilityName.getText() + "?",
							"Removing activity...", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
						modelActivity.removeRow(tableActivities
								.getSelectedRow());
						buttonRemoveA.setEnabled(false);
					}
				}
			});
			panel_1.add(buttonRemoveA);
			buttonRemoveA.setEnabled(false);

			buttonAddA = new JButton("Add");
			buttonAddA.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {

					Facility f = new Facility();

					if (!isNew) {
						f = (Facility) new FacilityCtr().getFacility(Long
								.parseLong(facilityID.getText()));
					}

					try {
						for (int i = 0; i < modelActivity.getRowCount(); i++) {
							System.out.println("Entry #" + i + ", data: "
									+ modelActivity.getValueAt(i, 0));
							if (!f.hasActivity((Long) modelActivity.getValueAt(
									i, 0)))
								f.addActivity(new ActivityTypeCtr()
										.getActivity((Long) modelActivity
												.getValueAt(i, 0)));
						}
					} catch (java.lang.ClassCastException e) {
						System.out
								.println("FacilityPanel - Error during 'Add Activity' : "
										+ e.getMessage());
					}

					Long ID = Long.parseLong((String) JOptionPane
							.showInputDialog(
									null,
									"Please enter activity ID to add: ",
									"Add activity to facility #"
											+ facilityID.getText(),
									JOptionPane.PLAIN_MESSAGE, null, null, null));

					if (new ActivityTypeCtr().activityExists(ID)
							&& !f.hasActivity(ID)) {
						f.addActivity(new ActivityTypeCtr().getActivity(ID));
					} else if (f.hasActivity(ID)) {
						JOptionPane
								.showMessageDialog(null,
										"Activity already added to facility!",
										"Add Activity Error",
										JOptionPane.ERROR_MESSAGE);
					} else {
						JOptionPane
								.showMessageDialog(null,
										"Activity does not exist!",
										"Add Activity Error",
										JOptionPane.ERROR_MESSAGE);
					}

					populateTableActivity(f);
				}
			});
			panel_1.add(buttonAddA);
			buttonAddA.setEnabled(false);
			panel_facility_activities.setLayout(gl_panel_facility_activities);

			JPanel panel_facility_edit = new JPanel();
			FlowLayout flowLayout = (FlowLayout) panel_facility_edit
					.getLayout();
			flowLayout.setAlignOnBaseline(true);
			panel_facilityDetail.add(panel_facility_edit, BorderLayout.SOUTH);

			btnNew = new JButton("New facility");
			btnNew.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					isNew = true;
					enableEdit();
				}
			});
			panel_facility_edit.add(btnNew);

			btnEdit = new JButton("Edit");
			btnEdit.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					isNew = false;
					enableEdit();
				}
			});
			btnEdit.setEnabled(false);
			panel_facility_edit.add(btnEdit);

			btnClear = new JButton("Clear");
			btnClear.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					enableClear();
					populateTableFacility();
				}
			});
			btnClear.setEnabled(false);
			panel_facility_edit.add(btnClear);

			btnDelete = new JButton("Delete");
			btnDelete.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					new FacilityCtr().removeFacility(new Long(facilityID
							.getText()));
					JOptionPane
							.showMessageDialog(null,
									"Facility deleted successfully!",
									"Facility Deleted",
									JOptionPane.INFORMATION_MESSAGE);
					enableClear();
					populateTableFacility();
				}
			});
			btnDelete.setEnabled(false);
			panel_facility_edit.add(btnDelete);

			btnSave = new JButton("Save");
			btnSave.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					FacilityCtr ctr = new FacilityCtr();
					if (isNew) {
						Facility f = new Facility();
						f.setName(facilityName.getText());
						ActivityTypeCtr actr = new ActivityTypeCtr();
						for (int row = 0; row < modelActivity.getRowCount(); row++) {
							f.addActivity(actr.getActivity((Long) modelActivity
									.getValueAt(row, 0)));
						}
						ctr.insertFacility(f);
						JOptionPane.showMessageDialog(null,
								"New facility added successfully!",
								"Facility added",
								JOptionPane.INFORMATION_MESSAGE);
					} else {
						Facility f = new Facility(
								new Long(facilityID.getText()));
						f.setName(facilityName.getText());
						ActivityTypeCtr actr = new ActivityTypeCtr();
						for (int row = 0; row < modelActivity.getRowCount(); row++) {
							f.addActivity(actr.getActivity((Long) modelActivity
									.getValueAt(row, 0)));
						}
						ctr.updateFacility(new Long(facilityID.getText()), f);
						JOptionPane.showMessageDialog(null, "Facility #"
								+ facilityID.getText() + " has been updated!",
								"Facility updated",
								JOptionPane.INFORMATION_MESSAGE);
					}
					isNew = false;
					enableClear();
					populateTableFacility();
				}
			});
			btnSave.setEnabled(false);
			panel_facility_edit.add(btnSave);
		}

		JPanel panel = new JPanel();
		panel_facilityList.add(panel, BorderLayout.NORTH);

		textField = new JTextField();
		textField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				populateTableFacility();
			}
		});
		textField.setColumns(30);

		btnRefresh = new JButton("Refresh");
		btnRefresh.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				populateTableFacility();
			}
		});

		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(gl_panel.createParallelGroup(
				Alignment.LEADING).addGroup(
				Alignment.TRAILING,
				gl_panel.createSequentialGroup()
						.addContainerGap()
						.addComponent(textField, GroupLayout.DEFAULT_SIZE, 381,
								Short.MAX_VALUE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(btnRefresh)));
		gl_panel.setVerticalGroup(gl_panel
				.createParallelGroup(Alignment.LEADING)
				.addGroup(
						gl_panel.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										gl_panel.createParallelGroup(
												Alignment.BASELINE)
												.addComponent(btnRefresh)
												.addComponent(
														textField,
														GroupLayout.PREFERRED_SIZE,
														23,
														GroupLayout.PREFERRED_SIZE))
								.addContainerGap(GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)));
		panel.setLayout(gl_panel);

		modelFacility = new DefaultTableModel(new Object[][] {}, new String[] {
				"ID", "Name", "Activities" }) {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};

		facilityTable = new JTable(modelFacility);
		facilityTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 1) {
					Facility f = new FacilityCtr()
							.getFacility((long) modelFacility.getValueAt(
									facilityTable.getSelectedRow(), 0));
					populateTableActivity(f);
					facilityID.setText(((Long) f.getID()).toString());
					facilityName.setText(f.getName());
					enableSelect();
				}
			}
		});
		facilityTable.getColumnModel().getColumn(0).setMaxWidth(50);
		panel_facilityList.add(new JScrollPane(facilityTable),
				BorderLayout.CENTER);

		populateTableFacility();
	}

	private void populateTableFacility() {

		ArrayList<Facility> facilities = new ArrayList<Facility>();

		if (textField.getText().length() > 0) {
			ArrayList<Facility> f2 = new FacilityCtr().getFacilities();
			for (Facility f : f2) {
				if (String.valueOf(f.getID()).toLowerCase()
						.contains(textField.getText().toLowerCase())
						|| f.getName().toLowerCase()
								.contains(textField.getText().toLowerCase()))
					facilities.add(f);
			}
		} else {
			facilities = new FacilityCtr().getFacilities();
		}

		modelFacility.setRowCount(0);
		for (Facility f : facilities) {
			modelFacility.addRow(new Object[] { f.getID(), f.getName(),
					generateActivityList(f) });
		}
	}

	private String generateActivityList(Facility f) {
		String activities = new String();
		ActivityTypeCtr a_ctr = new ActivityTypeCtr();

		for (ActivityType at : f.getActivities()) {
			ActivityType a = a_ctr.getActivity(at.getID());
			System.out.println(a.getName());
			activities += a.getName() + ", ";
		}

		System.out.println(f.getName() + " - " + activities);
		return activities;
	}

	private void populateTableActivity(Facility f) {
		modelActivity.setRowCount(0);
		ActivityTypeCtr a_ctr = new ActivityTypeCtr();

		for (ActivityType a : f.getActivities()) {
			ActivityType a2 = a_ctr.getActivity(a.getID());
			modelActivity.addRow(new Object[] { a2.getID(), a2.getName() });
		}
	}

	private void enableSelect() {
		btnEdit.setEnabled(true);
		btnClear.setEnabled(true);
		buttonAddA.setEnabled(false);
		btnSave.setEnabled(false);
		btnNew.setEnabled(false);
		btnDelete.setEnabled(false);
		tableActivities.setEnabled(false);
	}

	private void enableClear() {
		buttonAddA.setEnabled(false);
		buttonRemoveA.setEnabled(false);
		btnNew.setEnabled(true);
		btnEdit.setEnabled(false);
		btnClear.setEnabled(false);
		btnDelete.setEnabled(false);
		btnSave.setEnabled(false);
		facilityName.setText("");
		facilityName.setEnabled(false);
		facilityID.setText("");
		facilityID.setEnabled(false);
		tableActivities.setEnabled(false);
		modelActivity.setRowCount(0);
	}

	private void enableEdit() {
		if (isNew)
			btnDelete.setEnabled(false);
		else
			btnDelete.setEnabled(true);

		btnEdit.setEnabled(false);
		btnNew.setEnabled(false);
		tableActivities.setEnabled(true);
		btnSave.setEnabled(true);
		btnClear.setEnabled(true);
		buttonAddA.setEnabled(true);
		facilityName.setEnabled(true);
	}
}
